import { useRef, useImperativeHandle } from "react";
import PropTypes from "prop-types";

//在以前需要使用forwardRef，React19之后不再需要forwardRef,可以直接通过props获取

function ChildInput(props) {
  const inputRef = useRef();
  //通过useImperativeHandle自定义暴露给父组件的内容
  useImperativeHandle(props.ref, () => ({
    //ref.current =
    focus() {
      inputRef.current.focus();
    },
    getValue() {
      return inputRef.current.value;
    },
    setValue(value) {
      inputRef.current.value = value;
    },
  }));
  return <input ref={inputRef} />;
}
ChildInput.propTypes = {
  ref: PropTypes.object.isRequired,
};
function App() {
  const childRef = useRef();
  const handleClick = () => {
    childRef.current.focus();
    childRef.current.setValue("你好");
    console.log(childRef.current.getValue());
  };
  return (
    <div>
      <h3>Ref传递</h3>
      <ChildInput ref={childRef} />
      <button onClick={handleClick}>设置输入值</button>
    </div>
  );
}
export default App;
